import { Component, OnInit, Host, ViewChild } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { EventsService } from './events.service';
import { Page } from '../../../shared/components/table/models/pagination.model';
import { TableButton, ButtonType } from '../../../shared/components/table/models/tableButton.model';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';
import { TableComponent, PaginationPositionDisplayEnum } from '../../../shared/components/table/table.component';
import { ColumnOptions, ColumnType } from '../../../shared/components/table/models/columnOptions.model';
import { EventType, EventStatus } from './models/events.model';
import { ToasterService } from 'angular2-toaster';
import swal, { SweetAlertOptions } from 'sweetalert2';


@Component({
  templateUrl: './events.component.html',
  providers: [EventsService]
})
export class EventsComponent implements OnInit {
  private options: TableOptions;
  public events: any[];
  public selectedEvents: any[] = [];
  public count: number;
  public selectedType: EventType = undefined;
  public types = EventType;
  public paginationPosition = PaginationPositionDisplayEnum.Down;
  public columns: ColumnOptions[] = [
    new ColumnOptions('selected', 'Select', 'col-md-1', false, ColumnType.Buttons),
    new ColumnOptions('name', 'Event Name', 'col-md-3', true, ColumnType.Link),
    new ColumnOptions('start', 'Start Date', 'col-md-2', false, ColumnType.DateTime),
    new ColumnOptions('end', 'End Date', 'col-md-2', false, ColumnType.DateTime),
    new ColumnOptions('addedBy', 'Added by', 'col-md-2', false, ColumnType.Label),
    new ColumnOptions('status', 'Status', 'col-md-1', false, ColumnType.Label),
    new ColumnOptions('sponsorship', 'Sponsorship', 'col-md-1', false, ColumnType.Label)
  ];
  public filter: any = { name: '' };

  @ViewChild('eventsTable') eventsTable: TableComponent;

  constructor(@Host() private rootComponent: AppComponent,
    private eventsService: EventsService,
    private toasterService: ToasterService) { }

  ngOnInit() {
    this.options = new TableOptions('name');
    this.options.filter = this.filter;
    this.getEvents();
  }

  public getEvents(listOnly: boolean = false) {
    if (listOnly == false) {
      if (this.options.pageOptions.skip > 0) this.eventsTable.pageChanged(new Page(0, 20));
      this.eventsService.getEventsCount(this.options.filter.name, this.selectedType).subscribe(data => {
        this.count = data;
      });
    }

    this.eventsService.getEventsList(this.options.filter.name, this.selectedType, this.options.pageOptions.skip, this.options.pageOptions.take).subscribe(data => {
      this.events = data.items.map(event => {
        return {
          selected: [new TableButton('selected', { id: event.id, selected: this.selectedEvents.indexOf(event.id) > -1, status: event.status }, true, ButtonType.CheckBox)],
          name: new TableRouterLink(event.name, true, ['true', event.id]),
          start: new Date(event.startDate),
          end: new Date(event.endDate),
          addedBy: event.addedbyUserName,
          status: EventStatus[event.status],
          sponsorship: event.sponsorship ? 'Yes' : 'No'
        }
      });
      this.rootComponent.finishLoading();
    });
  }

  public tableOptionsChanged(tableOptions: TableOptions) {
    this.options = tableOptions;
    this.getEvents(tableOptions.pageOptions.listOnly);
  }

  public onEventSelectionChanged(event: any) {
    if (event.selected == false)
      this.selectedEvents.push({ id: event.id, status: event.status });
    else
      this.selectedEvents.splice(this.selectedEvents.findIndex(x => x.id == event.id), 1);
  }

  public deleteEvents() {
    const swalOptions: SweetAlertOptions = {
      buttonsStyling: false,
      customClass: 'modal-content',
      showCancelButton: true,
      title: 'Delete Events',
      text: 'A number of ' + this.selectedEvents.length + ' events will be removed. Are you sure that you want to continue?',
      confirmButtonClass: 'btn btn-primary',
      confirmButtonText: 'Delete',
      cancelButtonClass: 'btn btn btn-outline-dark-grey'
    };
    swal(swalOptions).then(result => {
      if (result && result.value) {
        this.eventsService.deleteEvents(this.selectedEvents.map(x => x.id)).subscribe(_ => {
          let ids: string[] = this.events.map(x => x.selected[0].actionOptions.id);
          for (var i = 0; i < ids.length; i++) {
            if (this.selectedEvents.findIndex(x => x.id == ids[i]) > -1) {
              this.events.splice(i, 1);
              ids.splice(i, 1);
              i--;
            }
          }
          this.eventsTable.updateSource(this.events);
          this.selectedEvents = [];
          this.toasterService.pop('success', 'Success', 'Events deleted successfull.');
        });
      }
    });
  }

  public publishEvents() {
    //check selected
    if (this.selectedEvents.findIndex(x => x.status != EventStatus.Draft) > -1)
      this.toasterService.pop('warning', 'Warning', 'Only items in status Draft can be published, please check your selection and try again.');
    else {
      const swalOptions: SweetAlertOptions = {
        buttonsStyling: false,
        customClass: 'modal-content',
        showCancelButton: true,
        title: 'Delete News',
        text: 'A number of ' + this.selectedEvents.length + ' events will be published. Are you sure that you want to continue?',
        confirmButtonClass: 'btn btn-primary',
        confirmButtonText: 'Publish',
        cancelButtonClass: 'btn btn btn-outline-dark-grey'
      };
      swal(swalOptions).then(result => {
        if (result && result.value) {
          this.eventsService.publishEvents(this.selectedEvents.map(x => x.id)).subscribe(_ => {
            this.events.filter(x => this.selectedEvents.findIndex(y => y.id == x.selected[0].actionOptions.id) > -1).forEach(x => {
              x.status = EventStatus[EventStatus.Published];
              x.selected[0].actionOptions.selected = false;
            });
            this.eventsTable.updateSource(this.events);
            this.selectedEvents = [];
            this.toasterService.pop('success', 'Success', 'Events published successfull.');
          });
        }
      });
    }
  }
}
